package com.last1mile.commons;

import java.io.IOException;
import java.security.Key;

import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.crypto.OperationMode;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Component("pwdEnDe")
public class PwdEnDe {

    AesCipherService aesCipherService = new AesCipherService();

    BASE64Encoder    enc              = new BASE64Encoder();

    BASE64Decoder    denc             = new BASE64Decoder();

    public PwdEnDe() {
        super();
        aesCipherService.setMode(OperationMode.CBC);
    }

    public String[] encrypt(String pwdRawStr) {
        String encryptPwdKeyBase64str = null;
        String encryptPwdBase64str = null;

        Key key = aesCipherService.generateNewKey();
        encryptPwdKeyBase64str = enc.encode(key.getEncoded());

        ByteSource encryptByteSource = aesCipherService.encrypt(pwdRawStr.getBytes(), key.getEncoded());
        encryptPwdBase64str = encryptByteSource.toBase64();

        return new String[] { encryptPwdBase64str, encryptPwdKeyBase64str };
    }

    public String decrypt(String encryptPwdBase64str, String encryptPwdKeyBase64str) {
        String pwdRawStr = null;

        try {

            byte[] encryptPwdByte = denc.decodeBuffer(encryptPwdBase64str);

            byte[] encryptPwdKeyByte = denc.decodeBuffer(encryptPwdKeyBase64str);

            ByteSource pwdByteSource = aesCipherService.decrypt(encryptPwdByte, encryptPwdKeyByte);

            pwdRawStr = new String(pwdByteSource.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return pwdRawStr;
    }
}
